﻿/*
 * RegExpress
 * 
 * Copyright (c) 2010, Daniel McGaughran
 * 
 * Licensed under the Apache Licence, Version 2.0 (the "Licence");
 * you may not use this file except in compliance with the Licence.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 * 
 */

using System;
using System.Xml;


namespace RegExpressModel
{
	public class SettingsModel
	{
		private MainWindowModel _globalState;


		public SettingsModel(MainWindowModel globalState)
		{
			_globalState = globalState;

		}



		/// <summary>
		/// Restores the state from configuration file.
		/// </summary>
		/// <param name="filename">The filename.</param>
		/// <returns></returns>
		public bool RestoreStateFromFile(string filename)
		{
			XmlDocument settingsDocument = new XmlDocument();

			try
			{
				settingsDocument.Load(filename);
			}
			catch (Exception)
			{
				//Invalid filename, insufficient permissions, file not found
				return false;
			}

			bool sectionsLoaded = true;

			//All settings deserialisation happens here
			sectionsLoaded &= _globalState.WindowSettings.ExtractFromXml(settingsDocument.DocumentElement);
			sectionsLoaded &= _globalState.SlideSettings.ExtractFromXml(settingsDocument.DocumentElement);
			return sectionsLoaded;
		}



		/// <summary>
		/// Saves the state to a configuration file.
		/// </summary>
		/// <param name="filename">The filename.</param>
		/// <returns></returns>
		public bool SaveStateToFile(string filename)
		{
			XmlDocument settingsDocument = new XmlDocument();

			XmlElement rootElement = settingsDocument.CreateElement(Constants.UserSettingsRootNodeName);
			settingsDocument.AppendChild(rootElement);

			//All settings serialisation happens here
			_globalState.WindowSettings.SaveToXml(settingsDocument, rootElement);
			_globalState.SlideSettings.SaveToXml(settingsDocument, rootElement);

			try
			{
				settingsDocument.Save(filename);
			}
			catch (Exception)
			{
				//Insufficient permissions, invalid filename
				return false;
			}

			return true;
		}


	}
}
